package com.app.couponsharelife.ui.main.tribe.money

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.lcodecore.tkrefreshlayout.footer.LoadingView
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.CouponMoneyRecordBean
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.CouponMoneyForceRecordAdapter
import com.app.couponsharelife.ui.dialog.CouponMoneyIntroduceDialog
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.viewmodel.TribeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_coupon_money.*
import java.util.HashMap

class CouponMoneyActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_coupon_money

    private var page = 1

    private var mViewModel: TribeViewModel? = null

    private var money = "0"

    /**
     * 标记下拉刷新还是上拉加载
     */
    private var isRefresh = true

    override fun initViews() {
        if (intent.getStringExtra("money") != null)
            money = intent.getStringExtra("money")
        else {
            showToastMsg("数据错误，请退出重试")
            finish()
        }
        tvCouponMoney.text = String.format("券金：%s", money)
        ivBack.setOnClickListener { finish() }
        tvCouponMoneyIntroduce.setOnClickListener {
            CouponMoneyIntroduceDialog(this, R.style.DialogStyle, 1).show()
        }
        initRecyclerView()
        initRefreshLayout()
    }

    private fun initRecyclerView() {
        mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        mRecyclerView.adapter = CouponMoneyForceRecordAdapter(arrayListOf(PageTipBean("", 0, 0)), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {

            }
        })
    }

    private fun initRefreshLayout() {
        mRefreshLayout.setFloatRefresh(true)
        mRefreshLayout.setAutoLoadMore(true)
        mRefreshLayout.setEnableLoadmore(true)
        mRefreshLayout.setEnableOverScroll(false)
        val header = ProgressLayout(this)
        header.setColorSchemeResources(R.color.act_main_bot_nav_select_text_color)
        mRefreshLayout.setHeaderView(header)
        mRefreshLayout.setBottomView(LoadingView(this))
        mRefreshLayout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = false
                loadData()
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = true
                page = 1
                loadData()
            }
        })
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(TribeViewModel::class.java)
        if (!mViewModel!!.getCouponKingRecordPage()!!.hasObservers()) {
            mViewModel!!.getCouponKingRecordPage()!!.observe(this, Observer {
                if (it == null) {
                    handleError(parseErrorDate("数据出错啦"))
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.refreshGetCouponKingRecordPage(hashMapOf(), false)
                        handleError(parseErrorDate(it.error!!.message))
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.refreshGetCouponKingRecordPage(hashMapOf(), false)
                        handleError(parseErrorDate("数据出错啦"))
                    }
                    PageStatus.Content -> {
                        mViewModel!!.refreshGetCouponKingRecordPage(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            handleContent(it.data.data!!)
                        } else {
                            handleError(parseErrorDate("获取失败"))
                        }
                    }
                }
            })
        }
        loadData()
    }

    private fun handleContent(data: CouponMoneyRecordBean) {
        if (page == 1 && isRefresh) {
            mRefreshLayout.finishRefreshing()
        } else
            mRefreshLayout.finishLoadmore()
        if (data.records.isNotEmpty()) {
            page++
            (mRecyclerView.adapter as CouponMoneyForceRecordAdapter).setData(data.records, page)
        } else {
            handleError(parseErrorDate(if (page == 1) "暂无记录" else "暂无更多记录"))
        }
    }

    private fun handleError(pageTipBean: PageTipBean) {
        if (page == 1) {
            if (isRefresh) mRefreshLayout.finishRefreshing() else mRefreshLayout.finishLoadmore()
            if ((mRecyclerView.adapter as CouponMoneyForceRecordAdapter).list[0] is PageTipBean) {
                ((mRecyclerView.adapter as CouponMoneyForceRecordAdapter).list[0] as PageTipBean).tip = pageTipBean.tip
                ((mRecyclerView.adapter as CouponMoneyForceRecordAdapter).list[0] as PageTipBean).status = pageTipBean.status
                ((mRecyclerView.adapter as CouponMoneyForceRecordAdapter).list[0] as PageTipBean).src = pageTipBean.src
                (mRecyclerView.adapter as CouponMoneyForceRecordAdapter).notifyItemChanged(0)
            }
        } else {
            mRefreshLayout.finishLoadmore()
            showToastMsg(pageTipBean.tip)
        }
    }

    private fun loadData() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["pageNo"] = page.toString()
        mViewModel?.refreshGetCouponKingRecordPage(map, true)
    }
}
